<?php

namespace App\Http\Controllers\Admin;

use App\Models\GoodsSpec;
use App\Models\Spec;
use App\Models\SpecValue;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class SpecValueController extends Controller
{
	/**
	 * 规格属性列表
	 * User: Clannad ~ ☆
	 * DataTime：2019/11/15 0015 13:16
	 */
    public function index(Request $request,$id)
    {
		//判断规格是否存在
		$spec = Spec::findOrfail($id);

		$SpecValueList = SpecValue::query()
						->orderBy('id','desc')
						->where('spec_id',$id)
						->paginate(10);

		return view('admin.spec_value.index',compact('SpecValueList','spec'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.spec_value.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request,SpecValue $specValueModel,$spec_id)
    {
		$spec = Spec::findOrfail($spec_id);

		$data = $request->except('_token');
		$specValueModel->fill($data);

		$spec_value = $spec->spec_value()->save($specValueModel);

		if($spec_value->id){
		    return redirect()->route('admin.spec_value.index',['spec_id'=>$spec_id])->with('success','添加成功');
		}else{
			return back()->with('error','添加失败');
		}
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
		$spec_value = SpecValue::findOrfail($id);

		return view('admin.spec_value.edit',compact('spec_value'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
    	$spec_value = SpecValue::findOrFail($id);

    	$data = $request->except('_token');

    	$spec_value->fill($data);
    	$spec_value->update();

    	return redirect()->route('admin.spec_value.index',['spec_id'=>$spec_value->spec_id])->with('success','修改成功');

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //删除规格属性的时候，一定要判断该属性是否在使用中
		$spec_value = SpecValue::findOrfail($id);
		//销毁类型的时候，要判断有没有属性在用，在用的不可删除。
		$goods_spec = GoodsSpec::query()->where('spec_value_id',$id)->count();
		if($goods_spec){
			return back()->with('danger','该商品属性有商品在使用，请先删除在用的商品');
		}

		$spec_id = $spec_value->spec_id;

		$spec_value->delete();

		return redirect()->route('admin.spec_value.index',['spec_id'=>$spec_id])->with('success','删除成功');
    }
}
